<?php

namespace Unl\HomologacionBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Unl\HomologacionBundle\Entity\Persona;
use Unl\HomologacionBundle\Entity\Usuario;
use Unl\HomologacionBundle\Form\PersonaType;
use Symfony\Component\HttpFoundation\Response;

/**
 * Persona controller.
 *
 * @Route("/persona")
 */
class PersonaController extends Controller
{    
    /**
     * Lists all Persona entities.
     *
     * @Route("/", name="persona")
     * @Template()
     */
    public function indexAction()
    {
        $sample = new Persona();
        $sample->setNombre('');
        $sample->setCedula('');
        $sample->getUsuario()->setEnabled('');
        
        $searchForm = $this->createForm(new PersonaType(), $sample);
        $request = $this->getRequest();
        $searchForm->bindRequest($request);

        $em = $this->getDoctrine()->getEntityManager();
        
       if ($sample->getNombre() == '') { 
            if ($sample->getCedula() == '') {
                    $entities = $em->getRepository('UnlHomologacionBundle:Persona')->findAllByEstado($sample->getUsuario()->getEnabled());
            } else {
                    $entities = $em->getRepository('UnlHomologacionBundle:Persona')->findAllByCriterio($sample->getCedula());
            }
       }else { 
           $entities = $em->getRepository('UnlHomologacionBundle:Persona')->findAllByCriterio($sample->getNombre());
           
           
       }
            
       return array('entities' => $entities, 
                     'search_form' => $searchForm->createView());
        
        
        
//        $em = $this->getDoctrine()->getEntityManager();
//
//        $entities = $em->getRepository('UnlHomologacionBundle:Persona')->findAll();
//
//        return array('entities' => $entities);
      
        
    }

    /**
     * Finds and displays a Persona entity.
     *
     * @Route("/{id}/show", name="persona_show")
     * @Template()
     */
    public function showAction($id)
    {
        $em = $this->getDoctrine()->getEntityManager();

        $entity = $em->getRepository('UnlHomologacionBundle:Persona')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find Persona entity.');
        }

        $deleteForm = $this->createDeleteForm($id);

        return array(
            'entity'      => $entity,
            'delete_form' => $deleteForm->createView(),        );
    }

    /**
     * Displays a form to create a new Persona entity.
     *
     * @Route("/new", name="persona_new")
     * @Template()
     */
    public function newAction()
    {
        $entity = new Persona();
        $personaType = new PersonaType();
        $personaType->setOcultarUsuario(FALSE);
        $form   = $this->createForm($personaType, $entity);

        return array(
            'entity' => $entity,
            'edit_form'   => $form->createView()
        );
    }

    /**
     * Creates a new Persona entity.
     *
     * @Route("/create", name="persona_create")
     * @Method("post")
     * @Template("UnlHomologacionBundle:Persona:new.html.twig")
     */
    public function createAction()
    {
        $entity  = new Persona();
        $request = $this->getRequest();
        $personaType = new PersonaType();
        $personaType->setOcultarUsuario(FALSE);
        $form    = $this->createForm($personaType, $entity);
        $form->bindRequest($request);
        $nextPage = 'login';
      
        


        if ($form->isValid()) {
            $em = $this->getDoctrine()->getEntityManager();
            $nextPage = 'login';
            if ($this->get('security.context')->isGranted('ROLE_ADMINISTRADOR') === true){
                $nextPage = 'persona';
            } else {
                $entity->getUsuario()->setEnabled(true); 
            }
            
//            if($this->validarCedula($cedula)){
            $em->persist($entity);
            $em->flush();
//            }
            $em = $this->getDoctrine()->getEntityManager();
           return $this->redirect($this->generateUrl($nextPage, array('descripcion1' => $entity->__toString())));            
        
        }

        

            return array(
                'entity' => $entity,
                'edit_form'   => $form->createView()
            );

     
    }

    /**
     * Displays a form to edit an existing Persona entity.
     *
     * @Route("/edit/{id}", name="persona_edit")
     * @Template()
     */
    public function editAction($id)
    {
        $em = $this->getDoctrine()->getEntityManager();

        $entity = $em->getRepository('UnlHomologacionBundle:Persona')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find Persona entity.');
        }
        
        $personaType = new PersonaType();
        $personaType->setOcultarUsuario(TRUE);
//        $personaType->setUsuario($entity->getUsuario());
        $editForm = $this->createForm($personaType, $entity);
        $deleteForm = $this->createDeleteForm($id);

        //return new Response($response);
        
        
//        $roles = '';
//        foreach ($entity->getUsuario()->getRoles() as $rol){
//            $roles = $roles . ' ' . $rol;
//        }
        
        //return new Response($roles);
        return array(
            'entity'      => $entity,
            'edit_form'   => $editForm->createView(),
            'delete_form' => $deleteForm->createView(),
        );
    }

    /**
     * Edits an existing Persona entity.
     *
     * @Route("/update/{id}", name="persona_update")
     * @Method("post")
     * @Template("UnlHomologacionBundle:Persona:edit.html.twig")
     */
    public function updateAction($id)
    {
        $em = $this->getDoctrine()->getEntityManager();

        $entity = $em->getRepository('UnlHomologacionBundle:Persona')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find Persona entity.');
        }
        $personaType = new PersonaType();
        $personaType->setOcultarUsuario(TRUE);
        $editForm   = $this->createForm($personaType, $entity);
        $deleteForm = $this->createDeleteForm($id);
        $enabled = $entity->getUsuario()->getEnabled(); 
        $username = $entity->getUsuario()->getUsername();
        $roles = $entity->getUsuario()->getRoles();
       
        
        $request = $this->getRequest();
        $editForm->bindRequest($request);
        $password = $editForm->getData()->getUsuario()->getPlainPassword();
        $usuario = $this->container->get('security.context')->getToken()->getUser()->getUsername();
        $cedula= $editForm->getData()->getCedula();
        
        /*
        if($entity->getTipoIdentificacion() === 'cedula'){
            
            if($this->validarCedula($cedula)){
                $entity->getUsuario()->setUsername($username); 
            } else {
                return null;
            }
        } 
        */

        if ($editForm->isValid()) {
            $nextPage = 'inicio';

            if ($this->get('security.context')->isGranted('ROLE_ADMINISTRADOR') === true){
                $nextPage = 'persona';
            } else {
                $entity->getUsuario()->setEnabled($enabled);
                $entity->getUsuario()->setRoles($roles);
                
                }
            if ($entity->getUsuario()->getUsername()== $usuario){
                if($editForm->getData()->getUsuario()->getPlainPassword()){
                 $entity->getUsuario()->setPassword($password);
                 $entity->getUsuario()->setPlainPassword($password);
                }
            }

            
        
            
        
            
            $em->persist($entity);
            $em->flush();

            return $this->redirect($this->generateUrl($nextPage, array('descripcion' => $entity->__toString())));
        
        
}


        return array(
            'entity'      => $entity,
            'edit_form'   => $editForm->createView(),
            'delete_form' => $deleteForm->createView(),
         
        );
    }

    /**
     * Deletes a Persona entity.
     *
     * @Route("/{id}/delete", name="persona_delete")
     * @Method("post")
     */
    public function deleteAction($id)
    {
        $form = $this->createDeleteForm($id);
        $request = $this->getRequest();

        $form->bindRequest($request);

        if ($form->isValid()) {
            $em = $this->getDoctrine()->getEntityManager();
            $entity = $em->getRepository('UnlHomologacionBundle:Persona')->find($id);

            if (!$entity) {
                throw $this->createNotFoundException('Unable to find Persona entity.');
            }

            $eliminar=$entity->__toString();
            $em->remove($entity);
            $em->flush();
        }

        return $this->redirect($this->generateUrl('persona', array('eliminar'=> $eliminar)));
    }

    private function createDeleteForm($id)
    {
        return $this->createFormBuilder(array('id' => $id))
            ->add('id', 'hidden')
            ->getForm()
        ;
    }
        
}
